package com.webserver.controller;

import com.webserver.core.ClientHandler;
import com.webserver.entity.Article;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

public class ArticleController {

    private static File ARTICLE_DIR = new File("./articles");

    private static File staticDir;

    static{
        if(!ARTICLE_DIR.exists()){
            ARTICLE_DIR.mkdirs();
        }

        try {
            staticDir = new File(
                    ClientHandler.class.getClassLoader().getResource(
                            "./static"
                    ).toURI()
            );
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始发送文章");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        System.out.println(title+","+author+","+content);

        if (title==null || author==null || content==null){
            File file = new File(staticDir,"/myweb/article_fail.html");
            response.setContentFile(file);
            return;
        }
        Article article = new Article(title,author,content);
        File articleFile = new File(ARTICLE_DIR,title+".obj");
        if (!articleFile.exists()){
            try(
                    FileOutputStream fos = new FileOutputStream(articleFile);
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
            ){
                oos.writeObject(article);
                File file = new File(staticDir,"/myweb/article_success.html");
                response.setContentFile(file);
            }catch (IOException e){

            }
            return;
        }
        File file = new File(staticDir,"/myweb/article_fail.html");
        response.setContentFile(file);


        System.out.println("发送文章结束");

    }
}
